
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  query.view;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Vector;

import logger.PoolLogger;


import property.Order;
import property.Property;
import utility.CapitalChar;
import database.RecordSearch;
import dbmanager.Column;
import dbmanager.DBManager;
import dbmanager.GetIdName;

public class Query implements Reportview 
{
	String object;
	String path;
	String TYPE="type";
	String reportname="report";
	String QUERYSTRING="SELECT * FROM ";
	Hashtable<Object, Object>ReportMap=new Hashtable<Object, Object>();
	Hashtable<Object, Object>QueryMap=new Hashtable<Object, Object>();
	Vector<Object>ConditionMap=new Vector<Object>();
	Hashtable<Object, Object>result=new Hashtable<Object, Object>();
	Hashtable<Object, Object>table=new Hashtable<Object, Object>();
	Order order;
	String QUERY="query";
	String STORAGE="Storage";
	GetIdName gid;
	String packagename="query.view";
	static int maxcount=1;
	String ALIES="p_";
	int Querycount=1;
	Vector<Object> propertyvector=new Vector<Object>();
	String Buffer[]; 
	boolean flag=false;
	PoolLogger pl;
	
	public Query() 
	{
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	
	
	@SuppressWarnings("unchecked")
	public void getResult() 
	{
		if(!flag)
		{
			//QUERYSTRING = QUERYSTRING + reportname;
			Reportview reportview;
			table = order.getSequences(QUERY);
			ReportMap.putAll(QueryMap);
			
			for(int i=0;i<table.size();i++)
			{
				try 
				{	
					String classname=table.get(Integer.toString(i+1)).toString();
					if(ReportMap.containsKey(classname))
					{
						Class c =Class.forName("query.view."+CapitalChar.makeFirstCharCapital(classname));
						reportview = (Reportview) c.newInstance();
						reportview.initPool();
						if(QueryMap.containsKey(classname.toLowerCase()))
						{
							reportview.setObject(QueryMap.get(classname.toLowerCase()).toString());
							try {
								reportview.setReportMap(ReportMap);
							} catch (Exception e) 
							{
								e.printStackTrace();
							}
						}	
						else
							reportview.setReportMap(ReportMap);
						reportview.initializeData();
						reportview.setMaxQuerycount(Querycount);
						reportview.setQuery(QUERYSTRING);
						reportview.setQueryCount(Querycount);
						reportview.getResult();
						ReportMap.putAll(reportview.getReportMap());
						QUERYSTRING=reportview.getQuery();
					}
				}
				catch (ClassNotFoundException e) 
				{
					e.printStackTrace();
				}
				catch (InstantiationException e) 
				{
					e.printStackTrace();
				} 
				catch (Exception e) 
				{
					e.printStackTrace();
				}
			 }
		}	
	}

	public String [] getbuffer()
	{
		try {
			if(!flag)
			{
				ResultSet rs = DBManager.getSelect(QUERYSTRING);
				Vector<Object> Field = DBManager.getSelect(QUERYSTRING, '0');
				StringBuffer buffer = new StringBuffer();
				for(int i=0;i<Field.size();i++)
						buffer.append(Field.get(i)+"\t");
				buffer.append("\n");
				try 
				{
					while(rs.next())
					{
						for(int i=0;i<Field.size();i++)
						{
							buffer.append(rs.getString(Field.get(i).toString())+"\t");
						}
						buffer.append("\n");
					}
				}
				catch (SQLException e) 
				{
					e.printStackTrace();
				}
				System.out.println(buffer.toString());
				return buffer.toString().split("\n");
			}
		} catch (Exception e) 
		{
			e.printStackTrace();
		}	
		for(int i=0;i<Buffer.length;i++)
		System.out.println(Buffer[i]);
		return Buffer;
	}

	public void initializeData() 
	{	
		String reportid=gid.getId(reportname);
		Property property = new Property();
		property.setMid(reportid);
		property.setPid(TYPE);
		String type=property.getValue();
		if(type.equalsIgnoreCase("printreport"))
		{
			Hashtable<Object, Object> insertmap =new Hashtable<Object, Object>();
			insertmap.put("report_name", reportname);
			insertmap.put("process", "mod");
			insertmap.put("status", "0");
			DBManager.getInsert("report_master",insertmap);
		}
		else
		{	
			property.setPid(STORAGE);
			String storage = property.getValue();
			
			if(!storage.equals("no$"))
			{
				try 
				{
					@SuppressWarnings("unused")
					ResultSet rs = DBManager.getSelect("select * from "+reportname);
				}
				catch (Exception e) 
				{
					query.report.Report report = new query.report.Report();
					if(ReportMap.containsKey("value"))
					report.setValue(ReportMap.get("value").toString());
					report.initPool();
					report.setProcess("mod");
					report.setReportName(reportname);
					report.setConditionmap(ConditionMap);
					report.setObject(reportid);
					report.setrepoton("");
					report.initializeData();
					report.updateReport();
				}
			}
			if(storage.equals("no$"))
			{
				query.report.Report report = new query.report.Report();
				if(ReportMap.containsKey("value"))
				report.setValue(ReportMap.get("value").toString());
				report.initPool();
				report.setProcess("mod");
				report.setReportName(reportname);
				report.setObject(reportid);
				report.setConditionmap(ConditionMap);
				report.setrepoton("");
				report.initializeData();
				report.setReportmap(QueryMap);
				report.updateReport();
				flag =true;
				Buffer=report.getBuffer();
			}
			else
				{	
				QueryMap.clear();
				QueryMap.put("mid", reportid);
				QueryMap.put("pid", QUERY);
				QueryMap.put("td", "null");
				RecordSearch rs = new RecordSearch();
				rs.setConditionMap(QueryMap);
				String result[] = rs.getArrayFromResultSet();
				QueryMap.clear();
				String line[] = null;
				for(int i=0;i<result.length;i++)
				{
					String splitresult[] = result[i].split("\t");
					QueryMap.put("pid", QUERY);
					QueryMap.put("pv", splitresult[Column.pv_index-1]);
					rs.setConditionMap(QueryMap);
					line = rs.getArrayFromResultSet();	
				}
				QueryMap.clear();
				String split[] =line[0].split("\t");
				QueryMap.put("mid",split[Column.pv_index-1] );
				rs.setConditionMap(QueryMap);
				line = rs.getArrayFromResultSet();
				for (int i = 0; i < line.length; i++) 
				{
					String splitline[]=line[i].split("\t");
					String value = splitline[Column.pv_index-1];
					if(value.equals("0"))
						value = splitline[Column.vt_index-1];
					if(!propertyvector.contains(splitline[Column.pid_index-1]))
						QueryMap.put(gid.getItem(splitline[Column.pid_index-1]).toLowerCase(), value);
				}
			}
		}	
	}
	
	
	public void initPool() 
	{
		gid = new GetIdName();
		QUERY = gid.getId(QUERY);
		order = new Order();
		TYPE = gid.getId(TYPE);
		STORAGE = gid.getId(STORAGE);
		propertyvector.add(gid.getId("condition"));
		propertyvector.add(gid.getId("field"));
		propertyvector.add(gid.getId("in"));
		propertyvector.add(gid.getId("join"));
		propertyvector.add(gid.getId("query"));
		propertyvector.add(gid.getId("resultset"));
	}

	public void setObject(String object) 
	{
		this.object = object;  	
	}
	
	public void setReportMap(Hashtable<Object, Object> hashtable) 
	{
		ReportMap.putAll(hashtable);
		if(ReportMap.containsKey("report"))
			reportname = ReportMap.get("report").toString();
		if(Querycount==1)
			QUERYSTRING = QUERYSTRING + reportname.toLowerCase() + " " + ALIES + Querycount + " ";
	}
	
	public int getQuerycount()
	{
		return Querycount;
	}	
	public void setQueryCount(int count) 
	{
		this.Querycount = count+1;
	}
	@SuppressWarnings("static-access")
	public void setMaxQuerycount(int count) 
	{	
		if(maxcount<count)
			this.maxcount = count;
	}
	public String getQuery() 
	{
		return QUERYSTRING;
	}
	public void setQuery(String Query) 
	{
		this.QUERYSTRING =Query;
	}

	public void setReportName(String Reportname) 
	{	
	}
	
	public static void main(String[] args) 
	{
		/*Hashtable<Object, Object > map = new Hashtable<Object, Object>();
		map.put("report", "itemreport");
		Hashtable<Object, Object > map1 = new Hashtable<Object, Object>();
		map1.put(query.condition.Condition.CONDITIONFIELD,"grade");
		map1.put(query.condition.Condition.CONDITIONVALUE,"a");
		map1.put(query.condition.Condition.CONDITIONOPERATOR, "=");
		map1.put(query.condition.Condition.LOGICALOPERATOR, "and");
		Hashtable<Object, Object > map2 = new Hashtable<Object, Object>();
		map2.put(query.condition.Condition.CONDITIONFIELD,"uom");
		map2.put(query.condition.Condition.CONDITIONVALUE,"gm");
		map2.put(query.condition.Condition.CONDITIONOPERATOR, "=");
		Vector<Object> condition = new Vector<Object>();
		condition.add(map1);
		condition.add(map2);
		Hashtable<Object, Object > map6 = new Hashtable<Object, Object>();
		map6.put("condition",condition);
		map.put("condition",condition);
		Vector<Object> field = new Vector<Object>();
		Hashtable<Object, Object > map3 = new Hashtable<Object, Object>();
		map3.put("field","mastername");
		Hashtable<Object, Object > map4 = new Hashtable<Object, Object>();
		map4.put("field","itemcode");
		field.add(map3);
		field.add(map4);
		Hashtable<Object, Object > map5 = new Hashtable<Object, Object>();
		map5.put("field", field);
		map.put("field", map5);
		Hashtable<Object, Object > map7 = new Hashtable<Object, Object>();
		map7.put("field", "itemcode");
		Hashtable<Object, Object > map8 = new Hashtable<Object, Object>();
		map.put("report", "itemreqreport");*/
		/*map.put("key", "tid");*/
		//map.put("value", "1545");
		Hashtable<Object, Object > map9 = new Hashtable<Object, Object>();
	//	map9.put("field", "mastername");
	//	map.put("groupby", map9);
		 System.out.println(System.currentTimeMillis());
		Hashtable<Object, Object > newmap = new Hashtable<Object, Object>();
		//newmap.put("report", "guimaster_report");
		//newmap.put("value", "Item");
		//newmap.put("mastername","tata tea gold");
		//newmap.put("personcode", "asa");
		Query query =new Query();		
		query.initPool();
		Vector<Object> conditionvector =new Vector<Object>();
		conditionvector.add(newmap);
		query.SetConditionmap(conditionvector);
		//query.setReportname("Categoryreport");
		query.setReportname("Uomreport");
		
		query.initializeData();
		query.getResult();
		query.getbuffer();
		//System.out.println(System.currentTimeMillis());
	}
	
	public Hashtable<Object, Object> getReportMap() 
	{
		return ReportMap;
	}
	
	public void setReportname(String reportname)
	{
		this.reportname = reportname;
	}
	public void SetConditionmap(Vector<Object>Conditionmap)
	{
		this.ConditionMap.addAll(Conditionmap);
	}
}
